package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.Material;
import com.example.chamberlainserver.Service.MaterialService;
import com.example.chamberlainserver.Vo.Request.Material.MaterialQuery;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import com.example.chamberlainserver.dto.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 物资管理控制器
 */
@RestController
@RequestMapping("/material")
public class MaterialController {

    @Autowired
    private MaterialService materialService;

    /**
     * 添加物资
     * @param material 物资信息
     * @return 添加结果
     */
    @PostMapping("/add")
    public ResponseEntity<ApiResponse<Material>> addMaterial(@RequestBody Material material) {
        try {
            // 如果状态为空，设置默认状态为"正常"
            if (material.getStatus() == null || material.getStatus().isEmpty()) {
                material.setStatus("正常");
            }
            
            // 设置最后盘点时间为当前时间（如果未提供）
            if (material.getLastInventoryTime() == null) {
                material.setLastInventoryTime(LocalDateTime.now());
            }
            
            Material savedMaterial = materialService.addMaterial(material);
            return ResponseEntity.ok(ApiResponse.success("添加物资成功", savedMaterial));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("添加物资失败：" + e.getMessage()));
        }
    }

    /**
     * 更新物资信息
     * @param material 物资信息
     * @return 更新结果
     */
    @PutMapping("/update")
    public ResponseEntity<ApiResponse<Material>> updateMaterial(@RequestBody Material material) {
        try {
            Material updatedMaterial = materialService.updateMaterial(material);
            return ResponseEntity.ok(ApiResponse.success("更新物资成功", updatedMaterial));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新物资失败：" + e.getMessage()));
        }
    }

    /**
     * 删除物资
     * @param id 物资ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteMaterial(@PathVariable Long id) {
        try {
            boolean success = materialService.deleteMaterial(id);
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("删除物资成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("删除物资失败：物资不存在或已被删除"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除物资失败：" + e.getMessage()));
        }
    }

    /**
     * 根据ID获取物资
     * @param id 物资ID
     * @return 物资信息
     */
    @GetMapping("/get/{id}")
    public ResponseEntity<ApiResponse<Material>> getMaterialById(@PathVariable Long id) {
        try {
            Material material = materialService.getMaterialById(id);
            if (material != null) {
                return ResponseEntity.ok(ApiResponse.success("获取物资成功", material));
            } else {
                return ResponseEntity.ok(ApiResponse.error("获取物资失败：物资不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取物资失败：" + e.getMessage()));
        }
    }

    /**
     * 获取所有物资
     * @return 物资列表
     */
    @GetMapping("/list")
    public ResponseEntity<ApiResponse<List<Material>>> getAllMaterials() {
        try {
            List<Material> materials = materialService.getAllMaterials();
            return ResponseEntity.ok(ApiResponse.success("获取物资列表成功", materials));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取物资列表失败：" + e.getMessage()));
        }
    }

    /**
     * 根据分类ID获取物资
     * @param categoryId 分类ID
     * @return 物资列表
     */
    @GetMapping("/category/{categoryId}")
    public ResponseEntity<ApiResponse<List<Material>>> getMaterialsByCategory(@PathVariable Integer categoryId) {
        try {
            List<Material> materials = materialService.getMaterialsByCategory(categoryId);
            return ResponseEntity.ok(ApiResponse.success("获取分类物资成功", materials));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取分类物资失败：" + e.getMessage()));
        }
    }

    /**
     * 根据存放位置ID获取物资
     * @param locationId 存放位置ID
     * @return 物资列表
     */
    @GetMapping("/location/{locationId}")
    public ResponseEntity<ApiResponse<List<Material>>> getMaterialsByLocation(@PathVariable Integer locationId) {
        try {
            List<Material> materials = materialService.getMaterialsByLocation(locationId);
            return ResponseEntity.ok(ApiResponse.success("获取位置物资成功", materials));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取位置物资失败：" + e.getMessage()));
        }
    }

    /**
     * 根据物资名称搜索物资
     * @param name 物资名称关键字
     * @return 物资列表
     */
    @GetMapping("/search")
    public ResponseEntity<ApiResponse<List<Material>>> searchMaterials(@RequestParam String name) {
        try {
            List<Material> materials = materialService.searchMaterialsByName(name);
            return ResponseEntity.ok(ApiResponse.success("搜索物资成功", materials));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("搜索物资失败：" + e.getMessage()));
        }
    }

    /**
     * 获取库存不足的物资
     * @return 物资列表
     */
    @GetMapping("/low-stock")
    public ResponseEntity<ApiResponse<List<Material>>> getLowStockMaterials() {
        try {
            List<Material> materials = materialService.getLowStockMaterials();
            return ResponseEntity.ok(ApiResponse.success("获取库存不足物资成功", materials));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取库存不足物资失败：" + e.getMessage()));
        }
    }

    /**
     * 更新物资库存
     * @param id 物资ID
     * @param quantity 新的库存数量
     * @return 更新结果
     */
    @PutMapping("/update-stock/{id}")
    public ResponseEntity<ApiResponse<Material>> updateMaterialStock(
            @PathVariable Long id, 
            @RequestParam Integer quantity) {
        try {
            Material material = materialService.updateMaterialStock(id, quantity);
            return ResponseEntity.ok(ApiResponse.success("更新库存成功", material));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新库存失败：" + e.getMessage()));
        }
    }

    /**
     * 更新物资盘点时间
     * @param id 物资ID
     * @return 更新结果
     */
    @PutMapping("/inventory/{id}")
    public ResponseEntity<ApiResponse<Material>> updateInventoryTime(@PathVariable Long id) {
        try {
            Material material = materialService.updateInventoryTime(id, LocalDateTime.now());
            return ResponseEntity.ok(ApiResponse.success("更新盘点时间成功", material));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新盘点时间失败：" + e.getMessage()));
        }
    }
    
    /**
     * 分页查询物资列表
     * @param current 当前页码
     * @param pageSize 每页大小
     * @param materialName 物资名称
     * @param categoryId 分类ID
     * @param specification 规格型号
     * @param locationId 存放位置ID
     * @param responsiblePerson 负责人
     * @param status 物资状态
     * @param minQuantity 库存数量下限
     * @param maxQuantity 库存数量上限
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 分页结果
     */
    @GetMapping("/pagedList")
    public ResponseEntity<ApiResponse<PageResult<Material>>> getPagedMaterialList(
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "materialName", required = false) String materialName,
            @RequestParam(value = "categoryId", required = false) Integer categoryId,
            @RequestParam(value = "specification", required = false) String specification,
            @RequestParam(value = "locationId", required = false) Integer locationId,
            @RequestParam(value = "responsiblePerson", required = false) String responsiblePerson,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "minQuantity", required = false) Integer minQuantity,
            @RequestParam(value = "maxQuantity", required = false) Integer maxQuantity,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) {
        try {
            MaterialQuery materialQuery = new MaterialQuery();
            materialQuery.setCurrent(current);
            materialQuery.setPageSize(pageSize);
            materialQuery.setMaterialName(materialName);
            materialQuery.setCategoryId(categoryId);
            materialQuery.setSpecification(specification);
            materialQuery.setLocationId(locationId);
            materialQuery.setResponsiblePerson(responsiblePerson);
            materialQuery.setStatus(status);
            materialQuery.setMinQuantity(minQuantity);
            materialQuery.setMaxQuantity(maxQuantity);
            materialQuery.setStartDate(startDate);
            materialQuery.setEndDate(endDate);
            
            PageResult<Material> pageResult = materialService.getPagedMaterialList(materialQuery);
            return ResponseEntity.ok(ApiResponse.success("获取物资列表成功", pageResult));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取物资列表失败: " + e.getMessage()));
        }
    }
}